package com.yan.controller;

import com.yan.controller.viewModel.login.UserModel;
import com.yan.service.AdminService;
import com.yan.service.BooksService;
import com.yan.service.SysAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
public class LoginOutController {

    @Autowired
    private BooksService bookService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private SysAdminService sysAdminService;

    /**
     * 实现登录并跳转到相应角色界面
     */
    @RequestMapping("/login")
    public String login(UserModel user, int loginType, Model model, HttpSession session) {
       // 普通用户
        if(loginType==0) {
            model.addAttribute("msg", "请选择登录身份");
        } else if (loginType == 1) {
            UserModel users = bookService.selectUser(user);
            if (users != null) {
                session.setAttribute("user", users);
                return "redirect:/user/show";
            } else {
                model.addAttribute("msg", "账号或密码错误");
                return "login";
            }
        } else if (loginType == 2) {
            UserModel admin = adminService.getAdmin(user);
            if (admin != null) {
                session.setAttribute("admin", admin);
                return "redirect:/admin/show";
            } else {
                model.addAttribute("msg", "账号或密码错误");
                return "login";
            }
        } else if (loginType == 3) {
            UserModel sysAdmin = sysAdminService.getSysAdmin(user);
            if (sysAdmin != null) {
                session.setAttribute("sysAdmin", sysAdmin);
                return "redirect:/sysadmin/show";
            } else {
                model.addAttribute("msg", "账号或密码错误");
                return "login";
            }
        }
        return "login";

    }

    /**
     * 退出登陆
     */
    @RequestMapping("/quit")
    public String quit(HttpSession session) {
        if(session.getAttribute("user")!=null)
            session.removeAttribute("user");
        if(session.getAttribute("admin")!=null)
            session.removeAttribute("admin");
        if(session.getAttribute("sysAdmin")!=null)
            session.removeAttribute("sysAdmin");
        session.invalidate();
        return "redirect:/looker/index";
    }

}
